#!/usr/bin/env python
# coding: utf-8

from typing import Any, Coroutine
from textual import events
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Log, Input, Button, Static
from textual.events import Key
import textual

import grpc
import json
from rpc import service_pb2_grpc, service_pb2

class MessageHistory(Log):
    def add_mesasge(self, msg) -> None:
        self.write_line(msg)

    def on_mount(self) ->None:
        """Event handler called when widget is added to the app."""
        self.check_message()
        self.update_timer = self.set_interval(3, self.check_message, pause=True)
        self.update_timer.resume()

    def check_message(self) -> None:
        response = stub.fetchMessageList(service_pb2.FetchMessageList(destination=destination))
        msg_list = json.loads(response.message)
        for msg in msg_list:
            msg_key = msg['sender'] + msg['msg']
            if msg_key not in chat_history:
                self.add_mesasge(msg['sender'] + " - > " +msg['msg'])
                chat_history.add(msg_key)

class ChatEdit(Static):
    def compose(self) -> ComposeResult:
        yield Input(id='msg', type='text')
        yield Button('发送', id='send')       

class WeChatShadowClient(App):
    BINDINGS = [
        ('q', 'quit', "Quit"),
        ('ctrl+s', 'send', 'Send')
    ]
    CSS_PATH = "ui.tcss"

    def on_mount(self) -> None:
        self.title = "touch touch fish"

    def compose(self) -> ComposeResult:
        yield Header()
        yield MessageHistory(id='msgLog')
        yield ChatEdit()
        #yield Footer()
        self.dark = True

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Event handler called when a button is pressed."""
        button_id = event.button.id
        if button_id == 'send':
            self.action_send()

    def on_key(self, event: Key):
        if event.name == 'enter':
            self.action_send()


    def action_send(self) -> None:
        input = self.query_one("#msg")
        print(input.value)
        if not input.value:
            return
        stub.sendMessage(service_pb2.SendMessage(destination=destination, content=input.value))
        input.value = ""



chat_history = set()
destination = '靠力气赚钱心里才踏实'

if __name__ == "__main__":
    print("Will try to connect server ...")
    channel = grpc.insecure_channel("localhost:1369")
    stub = service_pb2_grpc.WechatServiceStub(channel)

    app = WeChatShadowClient()
    app.run()